<template>
  <div>
    <query-table ref="plan_table" :page-size="20"
                 :table-max-height="tableMaxHeight"
                 :columns="columns"
                 :append-buttons="appendQueryButtons" :query-fields="queryFields"
                 :detail-fields="infoFields" base-url="/plan_info"
                 v-loading="isLoading" selectable show-index/>

    <el-dialog
        width="80%"
        title="导入数据"
        :visible="showFeaImport"
        :close-on-click-modal="false"
        @close="showFeaImport=false"
    >
      <el-main>
        <upload-excel v-if="!preEvaluationExcelData" :on-success="handleFileParseSuccess"
                      :before-upload="beforeUpload"/>
        <excel-view v-if="preEvaluationExcelData" :data="preEvaluationExcelData" max-height="500"></excel-view>
        <el-divider/>
        <el-button style="float: right" type="primary" :loading="isLoading" @click="importExcel">确认并导入</el-button>
        <el-button v-if="preEvaluationExcelData" style="float: right;margin-right:10px;" :loading="isLoading"
                   @click="preEvaluationExcelData=null;">重新选择
        </el-button>
      </el-main>
    </el-dialog>
    <el-dialog
        :visible="showTaskParam"
        :close-on-click-modal="false"
        @close="showTaskParam=false">
      <div style="font-size:20px;text-align: center;padding-bottom: 10px;width:90%;margin: 0 auto;padding-top:30px">
          <span style="float:right;padding-right: 20px;margin-top: -20px;padding-bottom:5px;">
                      <font
                          style="font-size: 16px;color: black;font-weight: bold;padding-right: 335px">公共参数维护表</font>

        </span>
        <record-table :columns="paramColumns" :data="taskParamData[this.currentRow]"></record-table>
      </div>
      <div slot="footer" style="text-align: center;" class="dialog-footer">
        <el-button type="primary" :loading="isLoading" style="margin: auto" @click="saveTaskParam">保存</el-button>
        <el-button @click="() =>{this.showTaskParam = false}">关闭</el-button>
      </div>

    </el-dialog>
  </div>

</template>

<script>
import RecordTable from "../../components/record-table";

const moment = require('moment');
import excel from "../../util/excel";
import Upload from "../../components/upload";

export default {
  name: "planList",
  components: {RecordTable},
  $$route: {
    meta: {
      title: '方案管理'
    }
  },
  props: {
    //页面总体高度
    pageHeight: {
      type: Number,
      defaultValue: 500
    }
  },
  data() {
    return {
      showFeaImport: false,
      isLoading: false,
      showTaskParam: false,
      taskParamData: {},
      currentRow: '',
      preEvaluationExcelData: null,
      productTypeMap: [],
      productType: '',
      queryFields: [
        {
          id: 'name',
          name: '名称',
          colSpan: 5
        },
        {id: 'year', name: '年度', component: 'year-picker', colSpan: 4},
        {id: 'productType', name: '产品类型', colSpan: 4, component: {id: 'meta-select', type: 'product-type'}},
      ],
      columns: [
        {id: 'name', name: '名称',},
        {id: 'totalInvest', name: '建设投资', width: 120, unit: '万元'},
        {id: 'year', name: '年度', width: 50},
        {id: 'productType', name: '产品类型', width: 60, type: 'meta', source: 'product-type'},
        {id: 'planType', name: '方案类型', width: 100, type: 'meta', source: 'plan-type'},
        {
          id: 'state', name: '状态', component: {
            id: 'tag', getType: (val) => {
              if (val == 'complete') {
                return 'success';
              }
            }
          }, width: 90, type: 'meta', source: 'batch-state'
        },
        {id: 'createUser', name: '创建人', type: 'user', width: 100, showOverflowTooltip: true},
        {
          id: 'createTime', name: '创建时间', width: 80, formatter: (value) => {
            if (value === null) {
              return ''
            }
            let dt = new Date(value)
            return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
          }
        },
        {
          id: 'operation', name: '操作', type: 'button', width: 290, children: [
            {
              text: '详情', type: 'primary', click: (row) => {
                this.openPage('/plan/manage', row.id)
              }
            },
            {
              text: '编辑', operation: 'edit', isHide: (row) => {
                return row.state === "complete" || !this.checkPermission('plan:update')
              }
            },
            {
              text: '锁定', type: 'success', click: (row) => {
                this.lockManage(row, true);
              }, isHide: (row) => {
                return row.state === "complete";
              }, isDisabled: (row) => {
                return this.$store.state.user.id!=row.createUser;
              }
            },
            {
              text: '解锁', type: 'danger', click: (row) => {
                this.lockManage(row, false);
              }, isHide: (row) => {
                return row.state === "init" || !this.checkPermission('plan:unlock')
              }
            },
            {
              text: '删除', type: 'danger', operation: 'delete', isHide: (row) => {
                return (row.state === "complete" || !this.checkPermission('plan:delete'));
              }
            },
          ]
        },
      ],

      appendQueryButtons: [
        {text: '新增', type: 'success', operation: 'create',isHide:()=>{return !this.checkPermission("plan:create")}},
      ],
      infoFields: [
        {
          id: 'name',
          name: '名称',
          rules: [{required: true, message: "请输入名称", trigger: "blur"}],
          colSpan: 24,
        },
        {
          id: 'year',
          name: '年度',
          defaultValue: new Date().getFullYear(),
          colSpan: 12,
          component: {id: 'year-picker'}
        },
        {
          id: 'buildOffice',
          name: '建设单位',
          colSpan: 12,
          component: {
            id: 'data-select', dataUrl: '/company/children_company_set?companyId=21810',load:(dataList,val)=>{
              for (let i = dataList.length -1; i >=0; i--) {
                if (dataList[i].type != "sub_office" && dataList[i].type != 'branch_office') {
                  dataList.splice(i,1);
                }
              }
              dataList.sort((a, b) => {
                if(isNaN(a.sort)||isNaN(b.sort)) {
                  return 0;
                }
                return a.sort - b.sort;
              })
            }
          },
        },

        {
          id: 'productType',
          name: '产品类型',
          colSpan: 12,
          component: {
            id: 'meta-select', type: 'product-type', change: (val, data) => {
              this.productType = val
              data.productProperty = null
              data.capacityType = null
              data.displacementMethod = null
              data.region = null
              data.poolType = null
              data.oilGasField = null
              if(val =='oil') {
                data.modelId = '105f798a831d4d919662c96a3d13c59f'
              } else if(val =='gas') {
                data.modelId = 'e077d3a2e95a4e25afccc8e445bed938'
              }
            }, clearable: false
          },
          isDisabled: (row) => {
            return row.id
          },
          defaultValue: 'oil'
        },
        {
          id: 'planType',
          name: '方案类型',
          colSpan: 12,
          component: {
            id: 'meta-select', type: 'plan-type',
          },
          // isDisabled: (row) => {
          //   return row.id
          // },
          defaultValue: 'pool'
        },
        {
          id: 'productProperty',
          name: '油气品质',
          colSpan: 12,
          component: {id: 'meta-select', type: 'oil-product-property'},
          isHide: (row) => {
            return row.productType == 'gas'
          },
        },
        {
          id: 'productProperty',
          name: '油气品质',
          colSpan: 12,
          component: {id: 'meta-select', type: 'gas-product-property'},
          isHide: (row) => {
            return row.productType == 'oil'
          },
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 12,
          component: {id: 'meta-select', type: 'oil-capacity-type'},
          isHide: (row) => {
            return row.productType == 'gas'
          },
        },
        {
          id: 'capacityType',
          name: '产能类型',
          colSpan: 12,
          component: {id: 'meta-select', type: 'gas-capacity-type'},
          isHide: (row) => {
            return row.productType == 'oil'
          },

        },

        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 12,
          component: {id: 'meta-select', type: 'oil-displacement-method'},
          isHide: (row) => {

            return row.productType == 'gas'
          },

        },
        {
          id: 'displacementMethod',
          name: '驱替方式',
          colSpan: 12,
          component: {id: 'meta-select', type: 'gas-displacement-method'},
          isHide: (row) => {
            return row.productType == 'oil'
          },

        },
        {
          id: 'areaMark',
          name: '新老区',
          colSpan: 12,
          component: {id: 'meta-select', type: 'area-mark'},

        },
        {
          id: 'region',
          name: '大区',
          colSpan: 12,
          component: {
            id: 'data-select',
            getDataUrl: () => {
              return '/cascade/queryChildrenList?type=oil-region&parentSource=${productType}';
            },
            valueKey: 'source',
            defaultSelect: 'first'
            // load:(dataList,fieldData,field) => {
            //   debugger
            //   if(dataList&&dataList.length == 1) {
            //     fieldData.region = dataList[0].source;
            //   }
            // }
          },
          isDisabled: (row) => {
            return !row.productType
          },
          isHide: (row) => {
            return row.productType == 'gas'
          },
        },
        {
          id: 'region',
          name: '大区',
          colSpan: 12,
          component: {id: 'meta-select', type: 'gas-region'},
          isDisabled: (row) => {
            return !row.productType
          },
          isHide: (row) => {
            return row.productType == 'oil'
          },
        },

        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 12,
          component: {id: 'meta-select', type: 'oil-pool-type-new'},
          isHide: (row) => {
            return row.productType == 'gas'
          },
        },
        {
          id: 'poolType',
          name: '油气藏类型',
          colSpan: 12,
          component: {id: 'meta-select', type: 'gas-pool-type'},
          isHide: (row) => {
            return row.productType == 'oil'
          },
        },
        {
          id: 'oilGasField',
          name: '油气田',
          colSpan: 12,
          component: {
            id: 'data-select',
            getDataUrl: () => {
              return '/cascade/queryChildrenList?type=oil-field&parentSource=${productType}';
            },
            valueKey: 'source',
            load:(dataList,fieldData,field) => {
              if(dataList&&dataList.length == 1) {
                fieldData.oilGasField = dataList[0].source;
              }
            }
          },
          isDisabled: (row) => {
            return !row.productType
          },
        },
        {
          id: 'other1',
          name: '其他类型1',
          colSpan: 12,
          component: {id: 'meta-select', type: 'other1'},
        },
        {
          id: 'other2',
          name: '其他类型2',
          colSpan: 12,
          component: {id: 'meta-select', type: 'other2'},
        },
        {
          id: 'paramVersion',
          name: '公共参数',
          component: {
            id: 'data-select',
            dataUrl: '/settings/common_param_version/queryPublish',
            defaultSelect: 'first'
          },
          isDisabled: (row) => {
            return row.id
          },
          // isHide:()=>{return true},
          colSpan: 12,
          rules: [{required: true, message: "请选择公共参数", trigger: "blur"}],
        },
        {
          id: 'modelId',
          name: '评价模型',
          defaultValue: '105f798a831d4d919662c96a3d13c59f',
          component: {
            id: 'data-select',
            dataUrl: '/settings/model/publish/data',
          },
          isDisabled: (row) => {
            return row.id
          },
          rules: [{required: true, message: "请选择评价模型", trigger: "blur"}],
          colSpan: 12
        },

      ],
      paramColumns: [
        {name: '序号', id: 'index', readonly: true},
        {name: '年度', id: 'year', readonly: true},
        {name: '油价(元/吨)', id: 'price'},
        {name: '原油产量调整系数', id: 'oilAdjustRate'},
        {name: '投资调整系数', id: 'investAdjustRate'},
        {name: '成本调整系数', id: 'costAdjustRate'},
      ],
    }
  },
  computed: {
    //表格最大高度，自适应
    tableMaxHeight() {
      return this.pageHeight - 100;
    }
  },
  created() {
    this.loadMetaNameMap('product-type', map => {
      this.productTypeMap = map;
      this.productType = 'oil'
    })


  },
  methods: {
    lockManage(row, lockState) {
      this.$confirm('确定' + (lockState ? '锁定' : '解锁') + '【' + row.name + '】评价方案吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.openLoading('正在处理...');
        row.state = lockState ? "complete" : "init";
        let url = lockState ? "/plan_info/lock" : "/plan_info/unlock";
        this.$post(url, row, (response) => {
          if (response.code == 0) {
            this.$refs['plan_table'].reload();
          }
        },()=>{
          loading.close();
        })
      })
    },
    /**
     *导入文件解析
     */
    handleFileParseSuccess(workbook) {
      this.preEvaluationExcelData = excel.parseXlsxWorkbook(workbook);
    },
    beforeUpload(file) {
      this.files = file;
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (extension !== 'xlsx' && extension !== 'xls') {
        this.$message({
          message: '只能上传Excel（即后缀是.xlsx或者.xls)的文件.',
          type: 'warning'
        })
        return false;
      }
      if (isLt5M) {
        return true;
      }

      this.$message({
        message: '请不要上传大于5MB的文件.',
        type: 'warning'
      })
      return false;
    },
    importExcel(e) {
      if (!e.target || !e.target.files || !e.target.files.length) {
        e.target.files = this.files;
        // return;
      }
      const loading = this.openLoading('正在处理...');
      let formData = new FormData();
      formData.append("multipartFile", e.target.files[0])
      this.$message.success('模拟保存成功！');
      loading.close();
      this.showFeaImport = false;
    },
    uploadFile() {
      // 装载成formData数据
      this.isLoading = true;
      this.excelLoading = true;
      const formData = new FormData();
      formData.append('file', this.files, this.files.name);
      formData.append('projectId', this.projectInfo.id);
      axios.post(Vue.prototype.$ctx + '/feasibility_data/pre_eva_file/upload', formData, {
        'Content-type': 'multipart/form-data'
      }).then(response => {
        if (response.data.code == 0) {
          this.projectDetailData.preEvaluationFileId = response.data.data;
          this.excelLoading = true;
          this.$get('/feasibility_data/pre_eva_file/preview', {fileId: this.projectDetailData.preEvaluationFileId}, (response) => {
            this.projectDetailData.preEvaluationExcelData = response.data;
            this.preEvaluationExcelData = null;
          }, () => {
            this.excelLoading = false;
          });
          // this.$message.success("上传成功")
          this.showFeaImport = false;
        } else {
          this.$message.warning(response.data.msg);
        }
        this.isLoading = false;
        // 上传成功后的处理
      }, err => {
        console.error(err);
        this.$message.error("上传文件出错")
        this.isLoading = false;
        this.excelLoading = false;
        // 出现错误时的处理
      })
    },
  }
}
</script>
